<script setup>
import {onMounted, reactive, ref} from "vue";
import axios from "axios";
import {Plus} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'

const formInline = reactive({
  name: '',
  pageNum:1,
  pageSize:3
})
const total=ref(0);
const isAdd = ref(true); // 标记是添加还是修改
const saveOrUpdateVisible = ref(false);
const saveOrUpdateTitle = ref('添加');
const heartKnowledge=ref(
    {
      name:'',
      simplyintroduce:'',
      img:'',
      text:''
    }
)
const loacalUrl = 'http://localhost:8080/file/downLoad?fileName=';
const imageUrl=ref('');
const fileList = ref([]);
// 修改onEdit函数
const onEdit = row => {
  saveOrUpdateTitle.value = '编辑';
  saveOrUpdateVisible.value = true;
  heartKnowledge.value = { ...row };
  console.log('heartKnowledge',heartKnowledge.value)
  // 初始化图片列表
  const images = row.img?.split(',') || [];
  fileList.value = images.map(img => ({
    name: img,
    url: loacalUrl + img
  }));

  // 显示最后一张图片
  imageUrl.value = images.length > 0 ? loacalUrl + images[images.length - 1] : '';
  isAdd.value = false;
};

//去添加的页面
const onAdd = ()=>{
  saveOrUpdateTitle.value='添加'
  saveOrUpdateVisible.value=true
  heartKnowledge.value= {
    name:'',
    simplyintroduce:'',
    img:'',
    text:''
  }
  fileList.value=[]
  isAdd.value = true; // 设置为添加模式
}

// 取消
const closearticle = ()=>{
  saveOrUpdateVisible.value=false
  imageUrl.value=''
  fileList.value=[]
}

// 保存
//添加和修改
const savearticle = ()=>{
  if (saveOrUpdateTitle.value==='添加'){
    axios.post('addheartknowledge',heartKnowledge.value)
        .then(res => {
          console.log('res', res);
          console.log('heartKnowledge',heartKnowledge.value)
          getheartKnowledge()
          ElMessage({
            message: '添加成功！',
            type: 'success',
          })
        })
        .catch(err => {
          console.log('err', err)
        })
  }else if (saveOrUpdateTitle.value==='编辑'){
    axios.put('updateheartknowledge', heartKnowledge.value)
        .then(res => {
          console.log('res', res);
          getheartKnowledge()
          ElMessage({
            message: '修改成功！',
            type: 'success',
          })
        })
        .catch(err => {
          console.log(err)
        })
  }
  saveOrUpdateVisible.value=false
}

// 删除
const onDel = id=>{
  ElMessageBox.confirm(
      '真的要删除吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
            axios.delete('deleteheartknowledge',
                {
                  params: {
                    id: id
                  }
                })
                .then(res => {
                  console.log('res', res);
                  getheartKnowledge()
                  ElMessage({
                    message: '删除成功！',
                    type: 'success',
                  })
                })
                .catch(err => {
                  console.log('err', err);
                  ElMessage({
                    message: '删除失败！',
                    type: 'error',
                  })
                })
          }
      )
}

const onSubmit = () => {
  getheartKnowledge()
}

const tableData = ref()

// 分页
// 每页条数改变
const handleSizeChange = (val) => {
  formInline.pageSize=val
  formInline.pageNum=1
  getheartKnowledge()
}
const handleCurrentChange = (val) => {
  formInline.pageNum=val
  getheartKnowledge()
}

onMounted(()=>{
  console.log('页面加载了');
  getheartKnowledge()
})
// 定义一个方法,用来动态调用后端接口,获取文章列表

const getheartKnowledge=()=>{
  axios.get('heartknowledge',
      {params:formInline
      })
      .then(res=>{
        console.log('res',res);
        total.value=res.data.data.total;
        tableData.value = res.data.data.list;
      })
      .catch(err=>{
        console.log('err',err);
      })
}


//图片长传上传成功
const handleAvatarSuccess = (res, file) => {
  if(isAdd.value){
    //   添加模式,直接赋值
    heartKnowledge.value.img = res.data;
    imageUrl.value=URL.createObjectURL(file.raw);
  }else {
    //   修改模式,追加图片并更新最后一张
    const images = heartKnowledge.value.img ? heartKnowledge.value.img.split(",") : [];
    images.push(res.data);
    heartKnowledge.value.img = images.join(",");
    imageUrl.value=loacalUrl+res.data;
  }
};

// 修改文件移除处理
const handleRemove = (file, fileList) => {
  if (isAdd.value) {
    heartKnowledge.value.img = '';
    imageUrl.value = '';
  } else {
    // 过滤出剩余的图片并更新最后一张
    const remainFiles = fileList.map(f => f.response?.data || f.name);
    heartKnowledge.value.img = remainFiles.join(',');
    imageUrl.value = remainFiles.length > 0
        ? loacalUrl + remainFiles[remainFiles.pop()]
        : '';
  }
};

</script>

<template>
  <div class="about">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="输入文章关键字">
        <el-input v-model="formInline.name" placeholder="请输入" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>



    <div class="mb20">
      <el-button @click="onAdd" type="primary" icon="Plus" plain>新增</el-button>
      <el-button type="danger" icon="Delete" plain>删除</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column fixed prop="id" label="编号" width="150" />
      <el-table-column prop="name" label="标题" width="120" />
      <el-table-column prop="simplyintroduce" label="简介" width="120" />
      <el-table-column prop="img" label="图片" width="120" >
        <template #default="scope">
          <el-image
              v-if="scope.row.img"
              style="width: 100px; height: 100px"
              :src="loacalUrl + scope.row.img"
          />
        </template>
      </el-table-column>
      <el-table-column prop="text" label="详情内容" width="120" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="onEdit(scope.row)">修改</el-button>
          <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="margin-top: 10px"
                   v-model:current-page="formInline.pageNum"
                   v-model:page-size="formInline.pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[1, 3, 5, 10]"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
    />
  </div>

  <!-- 添加，编辑弹框 -->
  <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="500">
    <el-form :model="heartKnowledge">
      <el-form-item label="标题" :label-width="formLabelWidth">
        <el-input v-model="heartKnowledge.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="简介" :label-width="formLabelWidth">
        <el-input v-model="heartKnowledge.simplyintroduce" autocomplete="off" />
      </el-form-item>

      <el-form-item label="图片" :label-width="formLabelWidth">
        <el-upload
            v-model:file-list="fileList"
            class="avatar-uploader"
            list-type="picture-card"
            action="http://localhost:8080/file/upload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :limit="isAdd ? 1 : Infinity"
            :on-exceed="handleExceed"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情内容" :label-width="formLabelWidth">
        <el-input v-model="heartKnowledge.text" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closearticle">取消</el-button>
        <el-button type="primary" @click="savearticle">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display:  none;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>